import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:studymanage/core/event_bus.dart';
import 'package:studymanage/core/global.dart';
import 'package:studymanage/login/protocol.dart';
import 'package:studymanage/mine/registered.dart';
import 'package:studymanage/util/project_config.dart';
import 'package:studymanage/util/request.dart';
import 'package:url_launcher/url_launcher.dart';

import '../home.dart';

class Login extends StatefulWidget {
  //1,正常 ，2是异常 不再发出请求
  final int type;

  Login(this.type);

  @override
  State<StatefulWidget> createState() {
    return LoginState();
  }
}

class LoginState extends State<Login>{
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  StreamSubscription _colorSubscription;
  Timer timer ;
  bool _hasRead = false;
  bool _isNeedUpdate = false; // 是否需要更新
  String phone;
  String verificationCode;
  int recode = 0;
  String verison="";

  double _progress = 0;
  int _updateType = 0;
  String _downUrl ;
  @override
  void initState() {
    setState(() {
       _colorSubscription =  eventBus.on<RequestEvent>().listen((messageEvent) {
        if (messageEvent.responseModel.code != 200) {
          Fluttertoast.showToast(
              msg: messageEvent.responseModel.msg,
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.TOP,
              textColor: Colors.white,
              backgroundColor: Colors.grey,
              fontSize: 12
          );
          if(messageEvent.responseModel.code ==401){
            Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) =>Login(2)), (route) => false);
          }
        }
      });
    });

    super.initState();
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 668, allowFontScaling: true)..init(context);

    return Scaffold(
      backgroundColor: Colors.white,
      body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child:SingleChildScrollView(
        child: Stack(
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: MediaQuery.of(context).size.width,
                    height: ScreenUtil().setHeight(250),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/images/login/login_bg.png'),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(59),
                          ),
                          child: Image.asset('assets/images/logo.png',
                            width: ScreenUtil().setHeight(118.5),
                            height: ScreenUtil().setHeight(118.5),
                            fit: BoxFit.fill,
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(16),
                          ),
                          child: Text('一家经营幸福感的情感教育平台',
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Light',
                              fontSize: ScreenUtil().setSp(14),
                              fontWeight: FontWeight.w300,
                              color: Colors.white,
                              letterSpacing: ScreenUtil().setSp(2),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Form(
                    key: _formKey,
                    child: Column(
                      children: <Widget>[
                        Container(
                          height: ScreenUtil().setHeight(50),
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(31),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Image.asset('assets/images/login/phone.png',
                                width: ScreenUtil().setWidth(23),
                                fit: BoxFit.fitWidth,
                              ),
                              Container(
                                width: ScreenUtil().setWidth(273.5),
                                margin: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(5),
                                ),
                                padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(5),
                                  right: ScreenUtil().setWidth(5),
                                ),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                      width: ScreenUtil().setHeight(0.5),
                                      color: Color.fromRGBO(238, 238, 238, 1),
                                    ),
                                  ),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    TextFormField(
                                      keyboardType: TextInputType.number,
                                      style: TextStyle(
                                        fontFamily: 'PingFangSC-Light',
                                        fontSize: ScreenUtil().setSp(16),
                                        color: Colors.black,
                                      ),
                                      decoration: InputDecoration(
                                        border: InputBorder.none,
                                        hintText: '请输入手机号',
                                        hintStyle: TextStyle(
                                          fontFamily: 'PingFangSC-Light',
                                          fontSize: ScreenUtil().setSp(14),
                                          color: Color.fromRGBO(133, 133, 133, 1),
                                        ),
                                      ),
                                      inputFormatters: <TextInputFormatter>[
                                        WhitelistingTextInputFormatter.digitsOnly,
                                        LengthLimitingTextInputFormatter(11)
                                      ],
                                      onSaved: (v) {
                                        setState(() {
                                          phone = v;
                                        });
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: ScreenUtil().setHeight(50),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Image.asset('assets/images/login/lock.png',
                                width: ScreenUtil().setWidth(23),
                                fit: BoxFit.fitWidth,
                              ),
                              Container(
                                width: ScreenUtil().setWidth(273.5),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                      width: ScreenUtil().setHeight(0.5),
                                      color: Color.fromRGBO(238, 238, 238, 1),
                                    ),
                                  ),
                                ),
                                margin: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(5),
                                ),
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      width: ScreenUtil().setWidth(185.5),
                                      padding: EdgeInsets.only(
                                        left: ScreenUtil().setWidth(5),
                                        right: ScreenUtil().setWidth(5),
                                      ),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: <Widget>[
                                          TextFormField(
                                            keyboardType: TextInputType.number,
                                            style: TextStyle(
                                              fontFamily: 'PingFangSC-Light',
                                              fontSize: ScreenUtil().setSp(16),
                                              color: Colors.black,
                                            ),
                                            decoration: InputDecoration(
                                              border: InputBorder.none,
                                              hintText: '请输入验证码',
                                              hintStyle: TextStyle(
                                                fontFamily: 'PingFangSC-Light',
                                                fontSize: ScreenUtil().setSp(14),
                                                color: Color.fromRGBO(133, 133, 133, 1),
                                              ),
                                            ),
                                            onSaved: (v) {
                                              setState(() {
                                                verificationCode = v;
                                              });
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                                    Container(
                                      width: ScreenUtil().setWidth(88),
                                      height: ScreenUtil().setHeight(60),
                                      color: Colors.white,
                                      child: FlatButton(
                                        padding: EdgeInsets.all(0),
                                        child: Text(recode == 0 ? '获取验证码' : recode.toString() + "S",
                                          style: TextStyle(
                                            fontFamily: 'PingFangSC-Light',
                                            fontSize: ScreenUtil().setSp(13),
                                            fontWeight: FontWeight.w300,
                                            color: Color.fromRGBO(51, 51, 51, 1),
                                          ),
                                        ),
                                        onPressed: recode ==0 ?()=> _sendCode() : null,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                            left: ScreenUtil().setWidth(35),
                            right: ScreenUtil().setWidth(35),
                            top: ScreenUtil().setHeight(61),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: ScreenUtil().setHeight(16),
                                height: ScreenUtil().setHeight(16),
                                margin: EdgeInsets.only(
                                  right: ScreenUtil().setWidth(7),
                                ),
                                child: Transform.scale(
                                  scale: 0.8,
                                  child: Theme(
                                    data: ThemeData(unselectedWidgetColor: Color.fromRGBO(216, 179, 137, 1)),
                                    child: Checkbox (
                                    activeColor: Color.fromRGBO(216, 179, 137, 1),

                                    value: _hasRead,
                                    onChanged: (bool val) {
                                      setState(() {
                                        _hasRead = val;
                                      });
                                    },
                                  )
                                  ),
                                ),
                              ),
                              Container(
                                child: Flexible(
                                  child: RichText(
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    text: TextSpan(
                                      text: '阅读并同意',
                                      style: TextStyle(
                                        fontFamily: 'PingFangSC-regular',
                                        fontSize: ScreenUtil().setSp(13),
                                        color: Color.fromRGBO(51, 51, 51, 1),
                                      ),
                                      children: <TextSpan> [
                                        TextSpan(
                                          text: '《瞳爱服务协议及用户隐私政策》',
                                          style: TextStyle(
                                            color: Color.fromRGBO(190, 181, 152, 1),
                                          ),
                                          recognizer: TapGestureRecognizer()..onTap = (){
                                            Navigator.push(context, MaterialPageRoute(builder: (context) => Protocol(()=>_agree())));
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          width: ScreenUtil().setWidth(300),
                          height: ScreenUtil().setHeight(45),
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(29),
                          ),
                          child: FlatButton(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(ScreenUtil().setHeight(4)),
                              ),
                            ),
                            color: Color.fromRGBO(210, 180, 142, 1),
                            child: Text('登录',
                              style: TextStyle(
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: ScreenUtil().setSp(18),
                                color: Colors.white,
                              ),
                            ),
                            onPressed: () {
                              _formKey.currentState.save();
                              if (phone.isEmpty ) {
                                Request().toast('请输入手机号');
                                return;
                              }
                              if (verificationCode.isEmpty) {
                                Request().toast('请输入验证码');
                                return;
                              }
                              if(phone.length != 11){
                                Request().toast('请输入正确的手机号');
                                return;
                              }
                              if (!_hasRead) {
                                Request().toast('请阅读用户协议');
                                return;
                              }
                              try {
                                Request().post<Map<String, dynamic>>(
                                    "/multiapi/open/login", data: {
                                  "phone": phone,
                                  "verificationCode": verificationCode
                                }).then((response) {
                                  if (response.code == 200) {
                                    _prefs.then((share) {
                                      Profile profile = Global.profile;
                                      profile.token = response.data['token'];
                                      profile.userTypeEnum = response.data['userTypeEnum'];
                                      profile.phone = phone.toString();
                                      Global.saveProfile();
                                      Request().toast('登录成功');
                                      _colorSubscription.cancel();
                                      if(response.data['userForm']){
                                        Navigator.push(context, MaterialPageRoute(builder: (context) => Registered()));

                                      }else{
                                          Navigator.pushAndRemoveUntil(context,
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  Home(response
                                                      .data['userTypeEnum'] == 1
                                                      ? Role.student
                                                      : Role.teacher)), (
                                              route) => false);
                                      }
                                    });
                                  }
                                });
                              } on DioError catch(e){
                                Request().toast(e.response.data['error_description']);
                              }
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Offstage(
                offstage: !_isNeedUpdate,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                  color: Colors.black.withOpacity(0.5),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CupertinoPopupSurface(
                        isSurfacePainted: false,
                        child: Container(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: ScreenUtil().setWidth(285),
                                height: ScreenUtil().setWidth(172),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                      width: ScreenUtil().setHeight(0.5),
                                      color: Colors.white,
                                    ),
                                  ),
                                  image: DecorationImage(
                                    image: AssetImage('assets/images/login/dialog_bg.png'),
                                    fit: BoxFit.fill,
                                  ),
                                ),
                                padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(26),
                                  top: ScreenUtil().setHeight(75),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text('发现新版本',
                                      style: TextStyle(
                                        fontFamily: 'PingFangSC-Medium',
                                        fontSize: ScreenUtil().setSp(20),
                                        fontWeight: FontWeight.w600,
                                        color: Colors.white,
                                        height: 1.4,
                                      ),
                                    ),
                                    Text(verison,
                                      style: TextStyle(
                                        fontFamily: 'PingFangSC-Medium',
                                        fontSize: ScreenUtil().setSp(20),
                                        fontWeight: FontWeight.w600,
                                        color: Colors.white,
                                        height: 1.4,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Container(
                                width: ScreenUtil().setWidth(284),
                                height: ScreenUtil().setHeight(90),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                    top: BorderSide(
                                      width: ScreenUtil().setHeight(0.5),
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      '现有新的版本更新',
                                      style: TextStyle(
                                        fontFamily: 'PingFangSC-Regular',
                                        fontSize: ScreenUtil().setSp(16),
                                        color: Color.fromRGBO(51, 51, 51, 1),
                                        letterSpacing: ScreenUtil().setSp(1),
                                        height: 1.47,
                                      ),
                                    ),
                                    Text(
                                      '请及时下载使用',
                                      style: TextStyle(
                                        fontFamily: 'PingFangSC-Regular',
                                        fontSize: ScreenUtil().setSp(16),
                                        color: Color.fromRGBO(51, 51, 51, 1),
                                        letterSpacing: ScreenUtil().setSp(1),
                                        height: 1.47,
                                      ),
                                    ),
                                    Offstage(
                                      offstage: _progress == 0,
                                      child: Text(
                                        '下载进度${_progress*100}%',
                                        style: TextStyle(
                                          fontFamily: 'PingFangSC-Regular',
                                          fontSize: ScreenUtil().setSp(12),
                                          color: Color.fromRGBO(51, 51, 51, 1),
                                          letterSpacing: ScreenUtil().setSp(1),
                                          height: 1.47,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Offstage(
                                offstage: _updateType == 0,
                                child: Container(
                                  width: ScreenUtil().setWidth(284),
                                  height: ScreenUtil().setHeight(44),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    border: Border(
                                      top: BorderSide(
                                        width: ScreenUtil().setHeight(0.5),
                                        color: Color.fromRGBO(238, 238, 238, 1),
                                      ),
                                    ),
                                  ),
                                  child: FlatButton(
                                    padding: EdgeInsets.all(0),
                                    child: Text(
                                      '取消更新',
                                      style: TextStyle(
                                        fontFamily: 'PingFangSC-Medium',
                                        fontSize: ScreenUtil().setSp(18),
                                        fontWeight: FontWeight.w600,
                                        color: Color.fromRGBO(210, 180, 142, 1),
                                        letterSpacing: ScreenUtil().setSp(1),
                                        height: 1.47,
                                      ),
                                    ),
                                    onPressed: () {
                                      setState(() {
                                        _isNeedUpdate = !_isNeedUpdate;
                                      });
                                    },
                                  ),
                                ),
                              ),
                              Container(
                                width: ScreenUtil().setWidth(284),
                                height: ScreenUtil().setHeight(44),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border(
                                    top: BorderSide(
                                      width: ScreenUtil().setHeight(0.5),
                                      color: Color.fromRGBO(238, 238, 238, 1),
                                    ),
                                  ),
                                ),
                                child: FlatButton(
                                  padding: EdgeInsets.all(0),
                                  child: Text(
                                    '立即更新',
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Medium',
                                      fontSize: ScreenUtil().setSp(18),
                                      fontWeight: FontWeight.w600,
                                      color: Color.fromRGBO(210, 180, 142, 1),
                                      letterSpacing: ScreenUtil().setSp(1),
                                      height: 1.47,
                                    ),
                                  ),
                                  onPressed: () =>_update(),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                )
            ),
          ],
        )
      )
      ),
    );

  }
    _agree(){
      setState(() {
        _hasRead = true;
      });
    }
    _sendCode(){
    if(recode!=0){
      return;
    }
     _formKey.currentState.save();
     if(phone.isEmpty){
       Request().toast( '手机号不能为空');
       return;
     }
     print("登陆");
     Request().post<Map<String, dynamic>>("/multiapi/open/sendMsg",data: {"phone":phone,}).then((response){
        if(response.code == 200){
          setState(() {
            recode = 60;
          });
          setState(() {
           timer = Timer.periodic(Duration(seconds: 1), (t) {
              setState(() {
                recode -=1;
              });
              if(t.tick == 60){
                t.cancel();
              }
            });
          });
        }
        Request().toast( '短信发送成功');
      });
    }
    _update() async {

      if (Platform.isIOS) {
        final url = "https://itunes.apple.com/cn/app/1505924629"; // id 后面的数字换成自己的应用 id 就行了
        if (await launch(url)) {
          await launch(url, forceSafariVC: false);
        } else {
          throw 'Could not launch $url';
        }
      }
      if(Platform.isAndroid) {
        bool status = await Permission.storage.isGranted;
        if (!status) {
          Permission.storage.request();
        }
        Directory storageDir = await getExternalStorageDirectory();
        String storagePath = storageDir.path;
        File file = new File('$storagePath/tongaiv${verison}.apk');

        file.parent.create();
        if (!file.existsSync()) {
          file.createSync();
        }
        if(_downUrl!=null){
          Response response = await Dio().get(
              _downUrl,
              onReceiveProgress: showDownloadProgress,
              options: Options(
                responseType: ResponseType.bytes,
                followRedirects: false,
              ));
          file.writeAsBytesSync(response.data);
          OpenFile.open(file.path);
        }else{
          Request().toast("下载地址为空");
        }

        print('更新');
      }

    }

  void showDownloadProgress(num received, num total) {
    if (total != -1) {
      double progress = double.parse('${(received / total).toStringAsFixed(2)}');
      setState(() {
        _progress = progress;
      });
    }
  }

  _checkVersion(){
    int appType = 0;
    if(Platform.isIOS){
      appType = 2;
    }
    if(Platform.isAndroid){
      appType = 1;
    }
    PackageInfo.fromPlatform().then((packageInfo) {
      Request()
          .post<Map<String, dynamic>>("/multiapi/open/c181v_version",data: {"version":packageInfo.version,"appType":appType})
          .then((response) {
        if(response.code == 200){
          if (packageInfo.version != response.data['version']) {
            setState(() {
              verison = response.data['version'];
              _isNeedUpdate = true;
              _updateType=response.data['updateType'];
              _downUrl = response.data['downUrl'];
            });
          }
        }
      });
    });
  }

}